package com.example.poemtest.Activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.poemtest.R;
import com.example.poemtest.entity.UserInfoBean;
import com.example.poemtest.utils.Constant;
import com.example.poemtest.utils.FullScreenUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 登录页面
 */
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText editUser, editPsd;
    private Button btnLogin, btnLoginReg;
    private String user, psd;
    private int code;   //返回的状态码
    private String msgCon;  //返回的错误信息
    public static final int RESEND = 1, SEND = 2, SUCCESS = 3, CODEFALSE = 4, FALSE = 5;  //常量值
    private Handler myHandler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //处理子线程发送的消息
            String result = (String) msg.obj;
            try {
                JSONObject jsonObject = new JSONObject(result);
                code = jsonObject.getInt("code");
                msgCon = jsonObject.getString("msg");
                Log.e("状态码",code+"");
                Log.e("返回的提示信息：",msgCon);
                if (code == 200){
                    //解析json文件流
                    UserInfoBean userInfoBean = com.alibaba.fastjson.JSONObject.parseObject(result,UserInfoBean.class);
                    List<UserInfoBean.UserInfo> list = userInfoBean.getData();
                    UserInfoBean.UserInfo userInfo = list.get(0);
                    Constant.userId = userInfo.getUserId();
                    Constant.userName = userInfo.getUserName();
                    Constant.userPhoto = userInfo.getUserPhotoSrc();
                    Constant.userGrade = userInfo.getUserGrade();
                    Constant.userLevel = userInfo.getUserLevel();
                    //跳转到App
                    //改
                    Intent intent = new Intent(LoginActivity.this, BottomNavigationViewActivity.class);
                    intent.putExtra("id",1);
                    startActivity(intent);
                } else {
                    Toast.makeText(LoginActivity.this,msgCon,Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        FullScreenUtil.getInstance().fullScreen(this,true);
        //绑定控件
        getView();
        //获取用户的输入信息
        getInfo();
    }

    /**
     * 获取用户的输入信息
     */
    private void getInfo() {
        user = editUser.getText().toString();
        psd = editPsd.getText().toString();
    }

    /**
     * 绑定控件对象
     */
    private void getView() {
        editUser = findViewById(R.id.edit_user);
        editPsd = findViewById(R.id.edit_psd);
        btnLogin = findViewById(R.id.btn_login);
        btnLogin.setOnClickListener(this);
        btnLoginReg = findViewById(R.id.btn_register);
        btnLoginReg.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_login:
                //点击登录，传输数据到后端，进行处理
                //若无法查询到该用户信息，提示：您还未注册，无法进行登录
                //若查询到用户名与密码不匹配，提示：用户名或密码错误
                //若查询到用户名和密码一致，直接跳转进入App
                getCoon();
//                if (user.equals("123") && psd.equals("123")) {
//                    Intent intent = new Intent(this,BottomNavigationViewActivity.class);
//                    startActivity(intent);
//                }
                break;
            case R.id.btn_register:
                //点击注册按钮，直接跳转到注册页面
                Intent intent = new Intent(this,RegisterActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    /**
     * 获取网络连接
     */
    private void getCoon(){
        //向后端传递页面上获取的账号密码
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("userName",user);
            jsonObject.put("userPsd",psd);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MediaType type = MediaType.parse("application/json;charset=utf-8");
        Log.e("json请求",jsonObject.toString());
        RequestBody requestBody = RequestBody.create(type,""+jsonObject.toString());

        //创建okhtto请求的对象
        OkHttpClient okHttpClient = new OkHttpClient();
        //创建请求连接，url里面存放请求连接，get表示其实get请求
//        Request request = new Request.Builder()
//                .url("http://192.168.43.131:8080/userInfo/login")
//                .post(requestBody)
//                .build();
        Request request = new Request.Builder()
                .url("http://192.168.43.131:8080/userInfo/login?userName=" + editUser.getText().toString() + "&userPsd=" + editPsd.getText().toString())
                .build();
        Log.e("请求的地址",jsonObject.toString());
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp","请求失败");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //处理后端传递的数据
                Log.e("okhttp","请求成功");
                String responseDate = response.body().string();
                Log.e("返回的数据",responseDate);
                //数据源发送改变，需要更新界面，使用Handler
                Message message = new Message();
                message.obj = responseDate;
                myHandler.sendMessage(message);//发送到主线程的消息队列
            }
        });
    }

}